package net.qmgyl.demos.shardingjdbc.domain.entity;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import net.qmgyl.demos.shardingjdbc.domain.shared.Page;
import net.qmgyl.demos.shardingjdbc.domain.valueobj.UserQueryVo;
import net.qmgyl.demos.shardingjdbc.infrastructure.mapper.user.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author xzw
 * @date ${date}  mailto 741342093@qq.com
 */
@Component
@Slf4j
public class UserManagerImpl implements UserManager {


    @Resource
    private UserMapper userMapper;

    @Override
    public User create(String name, String phone) {
        User user = new User();
        user.setName(name);
        user.setPhone(phone);
        user.setGmtCreate(new Date());
        user.setGmtModified(new Date());
        userMapper.insert(user);
        return user;
    }

    @Override
    public User find(Long id) {
        User user = userMapper.selectById(id);
        return user;
    }

    @Override
    public Page<User> page(UserQueryVo userQueryVo) {
        IPage<User> iPage = userMapper.selectPage(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<User>(userQueryVo.getPageNum(), userQueryVo.getPageSize()),
                new LambdaQueryWrapper<User>()
                        .eq(User::getIsDeleted, 0)
                        .like(User::getName, userQueryVo.getNameHint()));

        return Page.create(userQueryVo.getPageNum(), userQueryVo.getPageSize(), iPage.getRecords(), (int) iPage.getTotal());
    }

    @Override
    public void editName(User user) {
        if (StringUtils.isBlank(user.getName())) {
            throw new IllegalStateException("编辑名称异常");
        }

        User update = new User();
        update.setId(user.getId());
        update.setName(user.getName());
        update.setGmtModified(new Date());
        this.userMapper.updateById(update);

    }
}
